package com.example.websocket.monitor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@RestController
@RequestMapping("monitor")
public class WebSocketController {

    @Autowired
    private WebSocketServer webSocketServer;

    @GetMapping(value = "/search")
    public List<MonitorData> onReceive(String batchNo) throws IOException {
        List<MonitorData> monitorDataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Random random = new Random();
            monitorDataList.add(MonitorData.builder()
                    .jobId(String.valueOf(i))
                    .batchNo(String.valueOf(random.nextInt(10)))
                    .build());
        }
        List<MonitorData> res = monitorDataList.stream().filter(e -> e.getBatchNo().equals(batchNo)).collect(Collectors.toList());
//        sendWSMsg(res);
        return res;
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMonitorData(){
        List<MonitorData> monitorDataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Random random = new Random();
            monitorDataList.add(MonitorData.builder()
                    .jobId(String.valueOf(i))
                    .batchNo(String.valueOf(random.nextInt(10)))
                    .build());
        }
        sendWSMsg(monitorDataList);
    }

    public void sendWSMsg(List<MonitorData> monitorDataList){
        try {
            webSocketServer.broadCastInfo(JSONObject.toJSONString(monitorDataList));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

